import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/record/record_logic.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../resources/colours.dart';
import '../../utils/utils.dart';
import '../../widgets/base/qkd_text.dart';
import 'channel_filter_page.dart';

class RecordPage extends StatefulWidget {
  const RecordPage({super.key});

  @override
  State<RecordPage> createState() => _RecordPageState();
}

class _RecordPageState extends State<RecordPage> with TickerProviderStateMixin{
  final RecordLogic logic = Get.put(RecordLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<RecordLogic>(
      builder: (logic) {
      return VisibilityDetector(
        key: const Key("record"),
        onVisibilityChanged: (VisibilityInfo info) {
          if(!info.visibleBounds.isEmpty){
            Utils.onEvent("sj_sjk");
          }
        },
        child: LoadingWidget<bool>(
          isLoading: logic.isLoading,
          loading: Container(),
          data: false,
          reconnect: logic.getRefresh,
          child: () => Stack(
            alignment: AlignmentDirectional.center,
            children: [
              ExtendedTabBarView(
                controller: logic.headController,
                children: List.generate(2, (index) => Column(
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: SizedBox(
                            height: 40,
                            child: Styles.tabbar(
                              key: ValueKey(logic.count),
                              tabs: logic.tabList[index].map((e) => QkdText(e)).toList(),
                              scrollable: true,
                              fontSize: 16,
                              labelColor: Colours.text,
                              labelPadding: const EdgeInsets.symmetric(horizontal: 9),
                              controller: index==0?logic.zqController:logic.lqController,
                              onTap: (value) => Utils.onEvent(
                                "data_match_chanel_switch",
                                params: {"channel": logic.tabList[index][value]}
                              )
                            ),
                          ),
                        ),
                        Stack(
                          children: [
                            Image.asset(Utils.getImgPath("record_channel_back.png"),width: 48),
                            Container(
                              width: 48,
                              height: 40,
                              alignment: Alignment.center,
                              child: Image.asset(width: 16,Utils.getImgPath("my_channel.png")),
                            ).tap(() async {
                              Utils.onEvent('data_match_chanel_setting');
                              var result = await Get.bottomSheet(
                                  const ChannelFilterPage(),
                                  settings: RouteSettings(
                                    arguments: index
                                  ),
                                  isScrollControlled: true,
                                  enableDrag: false,
                                  ignoreSafeArea: false);
                              await logic.updateData(index);
                              Future.delayed(const Duration(milliseconds: 200));
                              var position = logic.data?[index].indexWhere((element) =>
                              element.channelId == result);
                              if(position != null&& position!=-1) {
                                index == 0
                                    ? logic.zqController.animateTo(position+logic.initialPlace[index])
                                    : logic.lqController.animateTo(position+logic.initialPlace[index]);
                              }
                            }),
                          ],
                        )
                      ],
                    ),
                    Expanded(
                      child: ExtendedTabBarView(
                        key: ValueKey(logic.count),
                        controller: index==0?logic.zqController:logic.lqController,
                        children: logic.channelPages[index]
                      )
                    ),
                  ],
                )),
              ),
              Positioned(
                  bottom: 32,
                  child: choiceBar())
            ],
          ),
        ),
      );
    });
  }

  Widget choiceBar(){
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          decoration:
          BoxDecoration(
              borderRadius: BorderRadius.circular(17),
              boxShadow: [
                BoxShadow(
                    offset: const Offset(0, 4),
                    color: Colours.main.withOpacity(0.1),
                    blurRadius: 4
                )
              ]
          ),
          height: 34,
          child: Stack(
            children: [
              Positioned(
                left: 2,
                right: 2,
                top: 1,
                bottom: 1,
                child: Container(
                  height: 34,
                  decoration: BoxDecoration(
                      border: Border.all(
                          color: Colours.main.withOpacity(0.4), width: 0.5),
                      borderRadius: BorderRadius.circular(17),
                      color: Colours.white),
                ),
              ),
              Row(children: [
                item('足球', 'top_zq.png', 0),
                item('篮球', 'top_lq.png', 1),
              ]),
            ],
          ),
        ),
      ],
    );
  }

  Widget item(String title, String selectImage, int index) {
    bool select = index == logic.headIndex;
    return GestureDetector(
      onTap: () {
        logic.headIndex = index;
        logic.headController.animateTo(index);
        update();
        Utils.onEvent("data_ball_type", params: {"type": index ==0?"足球":"篮球"});
      },
      child: Container(
        height: 36,
        width: 66,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(18),
          gradient: select
              ? const LinearGradient(
              colors: [Color(0xFFF54D4F), Color(0xFFF53C6A)],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter)
              : null,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
          if (select)
            Image.asset(
              Utils.getImgPath(selectImage),
              width: 16,
            ),
          const SizedBox(width: 2),
          QkdText(title,
            color: select ? Colours.white : Colours.main, fontSize: 12,
          )
        ]),
      ),
    );
  }
}
